<template>
  <a-layout>
    <siderbar v-if="isShow"></siderbar>
    <a-layout>
      <headerbar v-if="isShow"></headerbar>
      <a-layout-content>
        <div class="main-wrapper" :class="{ 'all-view': !isShow }">
          <router-view v-slot="{ Component }">
            <keep-alive>
              <component :is="Component" v-if="$route.meta.keepAlive" />
            </keep-alive>
            <component :is="Component" v-if="!$route.meta.keepAlive" />
          </router-view>
        </div>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>
<script setup>
import { ref, watch, onMounted, onBeforeUnmount} from "vue";
import API from "@/api/system";
import siderbar from "./siderbar.vue";
import headerbar from "./headerbar.vue";
import { useRouter } from "vue-router";
import { Modal } from "ant-design-vue";
import { useGlobalStore } from "@/store/modules/global";
const store = useGlobalStore();
const router = useRouter();
const isShow = ref(true);
const open = ref(true);
const handleMessage = async(e)=>{
  if (e.data.type === "tip") {
    Modal.error({
      title: e.data.data.title,
      content: e.data.data.content,
    });
  }
}

const cozeRef = ref(null);
let client = null; // 存储 Coze 实例
const initAi = () => {
  console.log("初始化AI", client);

  if (client) {
    client.destroy();
  }

  client = new CozeWebSDK.WebChatClient({
    /**
     * Agent or app settings
     * for agent
     * @param config.bot_id - Agent ID.
     * for app
     * @param config.type - To integrate a Coze app, you must set the value to app.
     * @param config.isIframe - Whether to use the iframe method to open the chat box
     * @param config.appInfo.appId - AI app ID.
     * @param config.appInfo.workflowId - Workflow or chatflow ID.
     */
    config: {
      type: "bot",
      bot_id: "7533985913001541672",
      isIframe: false,
      inputPlaceholder: "发送",
    },
    /**
     * The auth property is used to configure the authentication method.
     * @param type - Authentication method, default type is 'unauth', which means no authentication is required; it is recommended to set it to 'token', which means authentication is done through PAT (Personal Access Token) or OAuth.
     * @param token - When the type is set to 'token', you need to configure the PAT (Personal Access Token) or OAuth access key.
     * @param onRefreshToken - When the access key expires, a new key can be set as needed.
     */
    auth: {
      type: "token",
      token: token.value,
      onRefreshToken: async () => "token",
    },
    /**
     * The userInfo parameter is used to set the display of agent user information in the chat box.
     * @param userInfo.id - ID of the agent user.
     * @param userInfo.url - URL address of the user's avatar.
     * @param userInfo.nickname - Nickname of the agent user.
     */
    userInfo: {
      id: "user",
      url: "https://lf-coze-web-cdn.coze.cn/obj/eden-cn/lm-lgvj/ljhwZthlaukjlkulzlp/coze/coze-logo.png",
      nickname: "",
    },
    ui: {
      /**
       * The ui.base parameter is used to add the overall UI effect of the chat window.
       * @param base.icon - Application icon URL.
       * @param base.layout - Layout style of the agent chat box window, which can be set as 'pc' or'mobile'.
       * @param base.lang - System language of the agent, which can be set as 'en' or 'zh-CN'.
       * @param base.zIndex - The z-index of the chat box.
       */
      base: {
        icon: "https://lib.fantasy-lab.com/images/ai-radius.png",
        layout: "pc",

        lang: "zh-CN",
        zIndex: 1000,
      },
      /**
       * Controls whether to display the top title bar and the close button
       * @param header.isShow - Whether to display the top title bar.
       * @param header.isNeedClose - Whether to display the close button.
       */
      header: {
        isShow: true,
        isNeedClose: true,
      },
      /**
       * Controls whether to display the floating ball at the bottom right corner of the page.
       */
      asstBtn: {
        isNeed: true,
      },
      /**
       * The ui.footer parameter is used to add the footer of the chat window.
       * @param footer.isShow - Whether to display the bottom copy module.
       * @param footer.expressionText - The text information displayed at the bottom.
       * @param footer.linkvars - The link copy and link address in the footer.
       */
      footer: {
        isShow: false,
        expressionText: "Powered by ...",
      },
      /**
       * Control the UI and basic capabilities of the chat box.
       * @param chatBot.title - The title of the chatbox
       * @param chatBot.uploadable - Whether file uploading is supported.
       * @param chatBot.width - The width of the agent window on PC is measured in px, default is 460.
       * @param chatBot.el - Container for setting the placement of the chat box (Element).
       */
      chatBot: {
        title: "AI实验助理",
        uploadable: true,
        width: 500,
        isNeedAudio: false,
        isNeedQuote: false,
        isNeedHistory: false, // 禁用历史记录
      },
    },
  });
  // CozeWebSDK.showChatBox();
};
const token = ref("");

const getToken = async () => {
  const res = await API.AiCozeAccessToken();
  token.value = res;
  initAi();
};
const handleBackButton = () => {
  console.log("用户点击了后退按钮");
  // 执行你的逻辑
  store.deleteSubTitle();
};
onMounted(async () => {
  await getToken();
  window.addEventListener("popstate", handleBackButton);
  window.addEventListener("message", handleMessage);
  //initAi()
});
onBeforeUnmount(() => {
  window.removeEventListener("popstate", handleBackButton);
  window.removeEventListener("message", handleMessage);
});
watch(
  () => router.currentRoute.value,
  (newPath) => {
    isShow.value = newPath?.meta?.isLayout;

    initAi();
  },
  {
    immediate: true,
    deep: true,
  }
);
</script>
<style>
.ab1ac9d9bab12da47298 {
  width: 120px !important;
  height: 120px !important;
}
</style>
<style lang="less" scoped>
.sider-wrapper {
  width: 218px;
  height: 100%;
  background: #2776ff;
}
.main-wrapper {
  padding: 12px;
  height: 100%;
  overflow: auto;
  background: #fafafa;
  &.all-view {
    padding: 0;
    height: 100%;
    width: 100%;
    background: none;
  }
}
</style>
